package ltd.nullpointer.tcp.core.resolver;

import com.boot2.core.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import ltd.nullpointer.tcp.core.constant.TCPEnum.ErrorCode;
import ltd.nullpointer.tcp.core.message.AbstractTCPMessage;
import ltd.nullpointer.tcp.core.message.ErrorMessage;

/**
 * @ClassName: ErrorMessageResolver.java
 * @Description: 错误消息
 * @author zhangweilin
 * @date 2018年1月21日 下午12:10:29
 *
 */
public class ErrorMessageResolver implements MessageResolver {

	@Override
	public AbstractTCPMessage resolver(ByteBuf byteBuf) {

		// 读取剩下全部字节
		int contentLength = byteBuf.readableBytes();
		final byte[] contentByte = new byte[contentLength];
		byteBuf.readBytes(contentByte);
		// String errCode = ByteUtils.byteArr2HexStr(contentByte);
		String content = ByteUtils.getString(contentByte);

		// ====以下为采用msgCode=063方案
		// String msgCode = StringUtils.substring(content, 0,3);
		// String errCode = StringUtils.substring(content, 3);

		// ====以下为不采用msgCode=063方案
		String errCode = content;

		System.out.println("content: " + content);
		System.out.println("errCode: " + errCode);
		try {
			Integer errCodeInt = Integer.valueOf(errCode);
			// Integer msgCodeInt=Integer.valueOf(msgCode);
			ErrorMessage errorMessage = new ErrorMessage(errCodeInt);
			errorMessage.setErrCode(errCodeInt);
			errorMessage.setErrMessage(ErrorCode.getName(errCodeInt));
			return errorMessage;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Boolean isNeedEncrypt() {
		return false;
	}
}
